<template>
  <Box>
    <h2 style="margin: 10px 15px" slot="title">预案信息</h2>
    <div slot="box">
      <a-form-model
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >

        <a-form-model-item ref="name" label="预案类别" prop="planCategory">
          <a-select v-model="form.planCategory" placeholder="请选择">
            <a-select-option v-for="item of this.li" :value="item.planName" :key="item">
              {{ item.planName }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item ref="name" label="预案名称" prop="name">
          <a-input v-model="form.name" placeholder="请输入"/>
        </a-form-model-item>
        <a-form-model-item ref="name" label="预案措施" prop="measures">
          <a-input type="textarea" v-model="form.measures" placeholder="请输入" />
        </a-form-model-item>
        <a-form-model-item ref="name" label="预案流程" prop="technologicalProcess">
          <a-input type="textarea" v-model="form.technologicalProcess" placeholder="请输入" />
        </a-form-model-item>
        <div class="list" style="display: flex">
          <a-form-model-item ref="name" label="参与人员">
            <div style="width: 100%;">
              <a-table :columns="columns" :data-source="data" bordered>
                <template slot="department" slot-scope="text, record">
                  <div key="department">
                    <a-tree-select
                      v-if="record.editable"
                      v-model="record.department"
                      :value="record.department"
                      style="width: 100%"
                      :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                      :tree-data="treeData"
                      placeholder="请选择部门"
                      tree-default-expand-all
                      @change="e => handleChange(e, record.id, 'department',e)"
                    >

                    </a-tree-select>
                    <!--                    <a-input-->
                    <!--                      v-if="record.editable"-->
                    <!--                      style="margin: -5px 0"-->
                    <!--                      :value="text"-->
                    <!--                      placeholder="请输入物资名称"-->
                    <!--                      @change="e => handleChange(e.target.value, record.id, 'department')"-->
                    <!--                    />-->
                    <template v-else>
                      {{ text }}
                    </template>
                  </div>
                </template>
                <template slot="name" slot-scope="text, record">
                  <div key="name">
                    <a-select
                      placeholder="请输入"
                      v-if="record.editable"
                      style="margin: -5px 0"
                      v-model="text"
                      :value="text"
                      @change="e => handleChange(text, record.id, 'name')"
                    >
                      <a-select-option v-for="(item, key) in names" :key="key" :value="item.realname">{{
                        item.realname
                      }}</a-select-option>
                    </a-select>
                    <template v-else>
                      {{ text }}
                    </template>
                  </div>
                </template>
                <template slot="duties" slot-scope="text, record">
                  <div key="duties">
                    <a-input
                      v-if="record.editable"
                      :disabled="true"
                      style="margin: -5px 0;width: 100%"
                      :value="text"
                      v-model="text"
                      @change="e => handleChange(text, record.id, 'duties')"
                    />
                    <template v-else>
                      {{ text }}
                    </template>
                  </div>
                </template>
                <template slot="responsibleContent" slot-scope="text, record">
                  <div key="responsibleContent">
                    <a-input
                      placeholder="请输入"
                      v-if="record.editable"
                      style="margin: -5px 0"
                      v-model="text"
                      :value="text"
                      @change="e => handleChange(text, record.id, 'responsibleContent')"
                    >

                    </a-input>

                    <template v-else>
                      {{ text }}
                    </template>
                  </div>
                </template>

                <template slot="operation" slot-scope="text, record">
                  <div class="editable-row-operations">
                    <span v-if="record.editable">
                      <a @click="() => save(record.id)">保存</a>
                      <a-popconfirm title="取消保存?" @confirm="() => cancel(record.id)">
                        <a>取消</a>
                      </a-popconfirm>
                    </span>
                    <span v-else>
                      <a @click="() => edit(record.id)">编辑</a>
                      <a-popconfirm title="确定要删除所编辑的内容?" @confirm="() => onDelete(record.id)">
                        <a href="javascript:;">删除</a>
                      </a-popconfirm>
                    </span>
                  </div>
                </template>
                <template slot="footer">
                  <a href="javascript:;" @click="handleAdd"> + 添加</a>
                </template>
              </a-table>
            </div>

          </a-form-model-item>
        </div>
        <a-form-model-item ref="from" label="上传附件">
          <a-button @click="showModal"> <a-icon type="upload" /> 上传附件 </a-button>
          <div v-if="bal">
            <span v-for="(item,index) of this.nameTitle" :key="index">{{ item }}，</span>
          </div>
          <div v-else style="color: #b1b1b1">
            支持扩展名：.rar .zip .doc .docx .pdf .jpg...
          </div>
        </a-form-model-item>
        <a-form-model-item style="display: flex">
          <a-button type="primary" @click="query">
            确定
          </a-button>
          <a-button style="margin-left: 10px;" @click="uploads">
            取消
          </a-button>
        </a-form-model-item>
      </a-form-model>
      <div>
        <a-modal v-model="visible" title="上传附件" @ok="handleOk1" width="600px" centered>
          <Input ref="inpute" @importData="inputse" @title="titles"></Input>
        </a-modal>
        <a-modal v-model="visible1" title="再次确认" @ok="handleOk">
          <div>您确定要修改此数据</div>
        </a-modal>
        <a-modal v-model="visible2" title="再次确认" @ok="handleOk2">
          <div>确定修改并启动改预案？</div>
        </a-modal>
      </div>
    </div>
  </Box>
</template>

<script>
import Box from '@/views/xlgc/Box/index'
import { getDictItemsFromCache } from '@api/api'
import { getfrom } from '@api/xlgc/lawCase'
import { detailsList, resCreate, topXiangping, updateWz } from '@api/xlgc/Res'
import {
  addManage,
  getList,
  getManageList,
  getTree, getTypeLints,
  getTypeList,
  getTypeLists,
  lookManage, relaunch,
  textManage
} from '@api/xlgc/plan'
import Input from './ImportModal'
export default {
  name: 'AddRes',
  components: { Box, Input },
  data() {
    return {
      fileLists: [],
      names: [],
      oldData: [],
      treeData: [],
      data: [],

      columns: [
        {
          title: '序号',
          dataIndex: 'index',
          width: 60,
          align: 'center',
          scopedSlots: { customRender: 'index' }
          // 序号分页后连续
        },
        {
          title: '部门',
          dataIndex: 'department',
          width: '18%',
          scopedSlots: { customRender: 'department' }
        },
        {
          title: '名称',
          dataIndex: 'name',
          width: '18%',
          scopedSlots: { customRender: 'name' }
        },
        {
          title: '职务',
          dataIndex: 'duties',
          width: '18%',
          scopedSlots: { customRender: 'duties' }
        },
        {
          title: '负责内容',
          dataIndex: 'responsibleContent',
          width: '18%',
          scopedSlots: { customRender: 'responsibleContent' }
        },
        {
          title: '操作',
          dataIndex: 'operation',
          width: '18%',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      editingKey: '',
      visible: false,
      visible1: false,
      visible2: false,
      fileList: [],
      labelCol: { span: 2 },
      wrapperCol: { span: 6 },
      diqu: {},
      other: '',
      pageFilter: {
        pageNo: 1,
        pageSize: 10
      },
      form: {
        technologicalProcess: '',
        planCategory: undefined,
        name: '',
        measures: ''
      },
      count: 1,
      rules: {
        planCategory: [{ required: true, message: '请选择预案类别', trigger: 'blur' }],
        name: [{ required: true, message: '请输入预案名称', trigger: 'blur' }],
        measures: [{ required: true, message: '请输入预案流程', trigger: 'blur' }],
        technologicalProcess: [{ required: true, message: '请输入预案措施', trigger: 'blur' }]
      },
      passCheck: false,
      pass1: false,
      pass2: false,
      pass3: false,
      li: [],
      bf: [],
      key: '',
      roleName: '',
      item: false,
      type: undefined,
      group: undefined,
      id: undefined,
      xp: undefined,
      nameTitle: [],
      bal:false
    }
  },
  mounted() {
    this.item = this.$route.query.item
    if (this.item) {
      this.AgencyDetails(this.$route.query.id)
    }
    getTree()
      .then(res => {
        console.log(res)
        this.bf = [...res.result]
        this.treeData = res.result
        this.huidaio(this.treeData)
        console.log(this.treeData)
      })
      .catch(e => {
        this.$message.warn('请求失败！')
      })
    this.refreshTable1()
  },
  methods: {
    titles(val){
      this.bal = true
      this.nameTitle.push(val)
    },
    AgencyDetails(val) {
      let con = 1
      lookManage(val)
        .then(response => {
          console.log(response)
          if (response.code == 200) {
            this.xq = response.result
            this.form.measures = this.xq.measures
            this.form.name = this.xq.name
            this.form.planCategory = this.xq.planCategory
            this.form.technologicalProcess = this.xq.technologicalProcess
            for (let item of this.xq.planUsers) {
              item.index = con
              con += 1
            }
            this.data = this.xq.planUsers
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    submitForm() {
      this.$refs.ruleForm.validate(valid => {
        console.log(valid)
        // this.passCheck = valid
        this.pass1 = valid
      })
    },
    refreshTable1() {
      getTypeLints()
        .then(res => {
          console.log(res)
          this.li = res
        })
        .catch(e => {
          this.$message.warn('请求失败！')
        })
    },
    uploads() {
      this.$router.push({ path: '/manage/list' })
    },
    showModal() {
      this.visible = true
    },
    inputse(val) {
      let arr = []
      arr.push({
        storageAddress: val.url,
        attribute: val.type,
        type: val.group
      })
      this.fileLists = arr
      console.log(this.fileLists)
    },
    huidaio(val) {
      for (let item of val) {
        item.value = item.title
        if (item.children != []) {
          this.huidaio(item.children)
        }
      }
    },

    query() {
      console.log(this.data)
      this.submitForm()
      this.data == [] ? this.pass2 = false : this.pass2 = true
      if (this.data !== []) {
        for (let item of this.data) {
          delete item.updateBy
          delete item.updateTime
          for (let index in item) {
            console.log(item[index])
            if (item[index] == `` || item[index] == undefined) {
              this.$message.error('请检查参与人员第' + item.index + '行数据', 3)
              console.log(item[index])
              this.pass3 = false
              break
            } else {
              this.pass3 = true
            }
          }
        }
      }
      if (this.pass1 && this.pass2 && this.pass3) {
        for (let item of this.data) {
          delete item.id
          delete item.index
          delete item.key
        }
        console.log(this.data)
        if (this.item === 'false') {
          let data = {
            planUsers: this.data,
            reservePlan: this.form
          }
          this.fileLists !== [] ? Object.assign(data, { fileUrl: this.fileLists }) : this.fileLists = []
          console.log(data)
          addManage(data).then(res => {
            console.log(res)
            if (res.success) {
              this.$message.success(res.message, 2)
              this.$router.push({ path: '/manage/list' })
            } else {
              this.$message.error(res.message)
            }
          }).catch(error => {
            // console.log(error)
            this.$message.error('未知错误，请联系开发人员')
          })
        } else {
          if(this.$route.query.tortuous){
            this.visible2 = true
          } else {
            this.visible1 = true
          }

        }
      } else {
        this.$message.error('请重新校验自己的数据')
      }
    },
    handleOk1() {
      this.visible1 = false
      this.$refs.inpute.handleOk()
    },
    handleOk() {
      for (let item of this.data) {
        item.planId = this.$route.query.id
        item.id = this.$route.query.id
      }
      let data = {
        planUsers: this.data,
        reservePlan: Object.assign({}, this.form, { id: this.$route.query.id })
      }
      this.fileLists == [] ? Object.assign(data, { fileUrl: Object.assign(this.fileLists, { planId: this.$route.query.id }) }) : this.fileLists = []
      console.log(data)
      textManage(data).then(res => {
        console.log(res)
        this.visible1 = false
        if (res.success) {
          this.$message.success('修改成功', 2)
          if(this.$route.query.tortuous){
            this.$router.back()
          } else {
            this.$router.push({ path: '/manage/list' })
          }

        } else {
          this.$message.error('请重新校验自己的数据')
        }
      }).catch(error => {
        // console.log(error)
        this.$message.error('未知错误，请联系开发人员')
      })
    },
    handleOk2(){
      for (let item of this.data) {
        item.planId = this.$route.query.id
        item.id = this.$route.query.id
      }
      let data = {
        eventId: Number(this.$route.query.eventId),
        eventType: this.$route.query.type,
        planUsers: this.data,
        reservePlan: Object.assign({}, this.form, { id: this.$route.query.id })

      }
      this.fileLists == [] ? Object.assign(data, { fileUrl: Object.assign(this.fileLists, { planId: this.$route.query.id }) }) : this.fileLists = []
      console.log(data)
      relaunch(data).then(res => {
        console.log(res)
        this.visible1 = false
        if (res.success) {
          this.$message.success('修改成功', 2)
          if(this.$route.query.tortuous){
            this.$router.back()
          } else {
            this.$router.push({ path: '/manage/list' })
          }

        } else {
          this.$message.error('请重新校验自己的数据')
        }
      }).catch(error => {
        // console.log(error)
        this.$message.error('未知错误，请联系开发人员')
      })
    },
    handleAdd() {
      let index = 1
      const { count, data } = this
      const newData = {
        id: this.count,
        key: this.count,
        index: this.count,
        userId: ``,
        department: ``,
        name: ``,
        duties: ``,
        editable: true,
        responsibleContent: ''
      }
      this.data = [...data, newData]
      console.log(this.data)
      this.count += 1
      // console.log('count:' + newData.id)
    },
    onDelete(id) {
      const dataSource = [...this.data]
      this.data = dataSource.filter(item => item.id !== id)
    },
    chaxun(val, text) {
      let a = text
      for (let item of val) {
        if (text == item.title) {
          this.key = item.key
        } else if (item.children != []) {
          this.chaxun(item.children, a)
        }
      }
    },
    handleChange(value, id, column, e) {
      console.log(value, id, column)
      const newData = [...this.data]
      const target = newData.find(item => id === item.id)
      if (target) {
        target[column] = value
        this.data = newData
      }
      if (value != undefined) {
        for (let item of this.names) {
          if (value == item.realname) {
            // this.roleName =  item.roleName
            for (let index of this.data) {
              if (item.realname == index.name) {
                index.duties = item.roleName
                index.userId = item.id
              }
            }
          }
        }
      }
      if (e != undefined) {
        this.chaxun(this.bf, e)
        getList({ departId: this.key }).then(res => {
          console.log(res)
          if (res.result.records) {
            this.names = res.result.records
          }
        }).catch(error => {

        })
      }
    },
    edit(id) {
      const newData = [...this.data]
      newData.forEach((item, index) => {
        // console.log(item.id, id)
        if (item.id == id) {
          let oldItem = Object.assign({}, item) // 拷贝出新的对象
          this.oldData[index] = oldItem // 当前对象保存到数组，预备取消操作复原用
          if (item) {
            item.editable = true
            this.data = newData
          }
        }
      })
    },
    save(id) {
      // console.log(this.data)
      let newData = [...this.data]
      // let newCacheData = [...this.cacheData];
      let target = newData.find(item => id === item.id)
      // let targetCache = newCacheData.find(item => key === item.key);
      if (target) {
        delete target.editable
        this.data = newData
      }
    },
    cancel(id) {
      this.data.forEach((item, index) => {
        if (item.id == id) {
          item.editable = true
          const target = this.oldData[index]
          if (target != undefined) {
            this.$set(this.data, index, target)
          }
        }
      })
    }
  },
  watch:{
    nameTitle:{
      deep:true,
      handler(a,b){
        this.nameTitle = a
      }
    }
  }
}
</script>

<style scoped>
.list {
  display: flex;
  flex-direction: column;
}

/deep/ .list .ant-form-item-control-wrapper {
  width: 100% !important;
}

/deep/ .list .ant-col-2 {
  width: 100px !important;
}
.editable-row-operations a {
  margin-right: 8px;
}
/deep/.ant-table-footer{
  display: flex;
  justify-content: center;
}
/deep/.list label::before {
  display: inline-block;
  margin-right: 4px;
  color: #f5222d;
  font-size: 14px;
  font-family: SimSun, sans-serif;
  line-height: 1;
  content: '*';
}
</style>
